﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using GalaSoft.MvvmLight.Threading;
using HIWSystem.Models;
using HIWSystem.Helpers;
using HIWSystem.Common;
using System.Windows;
using Microsoft.Office.Interop.Excel;
using DataTable = System.Data.DataTable;
using Application = System.Windows.Application;
using System.Threading;

namespace HIWSystem.ViewModel
{
    public class SnStatus
    {
        public string Status { get; set; }

    }
    public class WOQueryViewModel : ViewModelBase
    {
        #region 属性
        private bool isFirstFilterPN = true;
        private bool isFirstFilterWO = true;
        bool IsCompletedQuery = false;
        bool IsCompletedExport = true;
        //首次生成的原始数据集
        DataTable dtWO = new DataTable();
        DataTable dtSnLastStatus = new DataTable();
        DataTable dtTestLogs = new DataTable();
        //待导出报告的数据集《中间可能会进行筛选》
        DataTable dtWOReport = new DataTable();
        DataTable dtSnLastStatusReport = new DataTable();
        ObservableCollection<PartNumberEntity> backupPNs = null;
        ObservableCollection<WOEntity> backupWOs = null;
        private ObservableCollection<PartNumberEntity> pns;
        /// <summary>
        /// 机种实体集合
        /// </summary>
        public ObservableCollection<PartNumberEntity> PNs
        {
            get { return pns; }
            set { pns = value; this.RaisePropertyChanged(() => PNs); }
        }
        private PartNumberEntity selectedPartNumber;
        /// <summary>
        /// 选择的机种实体
        /// </summary>
        public PartNumberEntity SelectedPartNumber
        {
            get { return selectedPartNumber; }
            set { selectedPartNumber = value; this.RaisePropertyChanged(() => SelectedPartNumber); }
        }
        private string pn;
        /// <summary>
        /// 机种
        /// </summary>
        public string PN
        {
            get { return pn; }
            set { pn = value; this.RaisePropertyChanged(() => PN); }
        }
        private bool isOpenComboPNDropDown;
        /// <summary>
        /// 是否打开机种下拉框选项卡
        /// </summary>
        public bool IsOpenComboPNDropDown
        {
            get { return isOpenComboPNDropDown; }
            set { isOpenComboPNDropDown = value; this.RaisePropertyChanged(() => IsOpenComboPNDropDown); }
        }
        private string searchPNText;
        /// <summary>
        /// 机种下拉框中输入的文本内容
        /// </summary>
        public string SearchPNText
        {
            get { return searchPNText; }
            set { searchPNText = value; this.RaisePropertyChanged(() => SearchPNText); }
        }
        private ObservableCollection<WOEntity> wos;
        /// <summary>
        /// 工单实体集合
        /// </summary>
        public ObservableCollection<WOEntity> WOs
        {
            get { return wos; }
            set { wos = value; this.RaisePropertyChanged(() => WOs); }
        }
        private WOEntity selectedWO;
        /// <summary>
        /// 选择的工单实体
        /// </summary>
        public WOEntity SelectedWO
        {
            get { return selectedWO; }
            set { selectedWO = value; this.RaisePropertyChanged(() => SelectedWO); }
        }
        private string wo;
        /// <summary>
        /// 选择的工单
        /// </summary>
        public string WO
        {
            get { return wo; }
            set { wo = value; this.RaisePropertyChanged(() => WO); }
        }
        private bool isOpenComboWODropDown;
        /// <summary>
        /// 是否打开工单下拉框选项卡
        /// </summary>
        public bool IsOpenComboWODropDown
        {
            get { return isOpenComboWODropDown; }
            set { isOpenComboWODropDown = value; this.RaisePropertyChanged(() => IsOpenComboWODropDown); }
        }
        private string searchWOText;
        /// <summary>
        /// 工单下拉列表框中输入的文本
        /// </summary>
        public string SearchWOText
        {
            get { return searchWOText; }
            set { searchWOText = value; this.RaisePropertyChanged(() => SearchWOText); }
        }
        //private string pn;
        ///// <summary>
        ///// 机种
        ///// </summary>
        //public string PN
        //{
        //    get { return pn; }
        //    set { pn = value; this.RaisePropertyChanged(() => PN); }
        //}
        //private string wo;
        ///// <summary>
        ///// 工单
        ///// </summary>
        //public string WO
        //{
        //    get { return wo; }
        //    set { wo = value; this.RaisePropertyChanged(() => WO); }
        //}
        private string sn;
        /// <summary>
        /// 序列号
        /// </summary>
        public string SN
        {
            get { return sn; }
            set { sn = value; this.RaisePropertyChanged(() => SN); }
        }
        private ObservableCollection<WOEntity> WOsource;
        /// <summary>
        /// 工单详细信息
        /// </summary>
        public ObservableCollection<WOEntity> WOSource
        {
            get { return WOsource; }
            set { WOsource = value; this.RaisePropertyChanged(() => WOSource); }
        }
      
        private ObservableCollection<SNEntity> lastStatus;
        /// <summary>
        /// 序列号最后的状态信息
        /// </summary>
        public ObservableCollection<SNEntity> LastStatus
        {
            get { return lastStatus; }
            set { lastStatus = value; this.RaisePropertyChanged(() => LastStatus); }
        }
        private Visibility isVisibleLoading = Visibility.Collapsed;

        public Visibility IsVisibleLoading
        {
            get { return isVisibleLoading; }
            set { isVisibleLoading = value; this.RaisePropertyChanged(() => IsVisibleLoading); }
        }
        private bool isEnabledQueryButton=true;
        /// <summary>
        /// 是否启用查询按钮
        /// </summary>
        public bool IsEnabledQueryButton
        {
            get { return isEnabledQueryButton; }
            set { isEnabledQueryButton = value; this.RaisePropertyChanged(() => IsEnabledQueryButton); }
        }
        private bool isEnabledExportButton=true;
        /// <summary>
        /// 是否启用导出按钮
        /// </summary>
        public bool IsEnabledExportButton
        {
            get { return isEnabledExportButton; }
            set { isEnabledExportButton = value; this.RaisePropertyChanged(() => IsEnabledExportButton); }
        }

        private bool isCheckedAll=false;
        /// <summary>
        /// 是否选择全部查询
        /// </summary>
        public bool IsCheckedAll
        {
            get { return isCheckedAll; }
            set { isCheckedAll = value; this.RaisePropertyChanged(() => IsCheckedAll); }
        }
        private Visibility testLogPanelVisibile=Visibility.Collapsed;
        /// <summary>
        /// 是否显示测试Log的面板《当查询序列号的时候显示其它情况不显示》
        /// </summary>
        public Visibility TestLogPanelVisibile
        {
            get { return testLogPanelVisibile; }
            set { testLogPanelVisibile= value; this.RaisePropertyChanged(() => TestLogPanelVisibile); }
        }
        private ObservableCollection<TrackingEntity> testLogs;
        /// <summary>
        /// 测试log信息
        /// </summary>
        public ObservableCollection<TrackingEntity> TestLogs
        {
            get { return testLogs; }
            set { testLogs = value; this.RaisePropertyChanged(() => TestLogs); }
        }
        private ObservableCollection<SnStatus> snStatus;
        /// <summary>
        /// 序列号所有状态
        /// </summary>
        public ObservableCollection<SnStatus> SnStatus
        {
            get { return snStatus; }
            set { snStatus = value; this.RaisePropertyChanged(() => SnStatus); }
        }

        private SnStatus selectedStatus;
        /// <summary>
        /// 选择的序列号状态项
        /// </summary>
        public SnStatus SelectedStatus
        {
            get { return selectedStatus; }
            set { selectedStatus = value; this.RaisePropertyChanged(() => SelectedStatus); }
        }
        private string status;
        /// <summary>
        /// 序列号状态
        /// </summary>
        public string Status
        {
            get { return status; }
            set { status = value; this.RaisePropertyChanged(() => Status); }
        }
        private ObservableCollection<WOEntity> woStates;
        /// <summary>
        /// 工单的状态集合
        /// </summary>
        public ObservableCollection<WOEntity> WOStates
        {
            get { return woStates; }
            set { woStates = value; this.RaisePropertyChanged(() => WOStates); }
        }
        private WOEntity selectedWOState;
        /// <summary>
        /// 选择的工单状态实体
        /// </summary>
        public WOEntity SelectedWOState
        {
            get { return selectedWOState; }
            set { selectedWOState = value; this.RaisePropertyChanged(() => SelectedWOState); }
        }
        private string woState;
        /// <summary>
        /// 工单状态
        /// </summary>
        public string WOState
        {
            get { return woState; }
            set { woState = value; this.RaisePropertyChanged(() => WOState); }
        }

        #endregion

        #region 命令
        private RelayCommand loadPageCmd;

        public RelayCommand LoadPageCmd
        {
            get
            {
                if (loadPageCmd == null)
                {
                    loadPageCmd = new RelayCommand(LoadPage);
                }
                return loadPageCmd;
            }
            set { loadPageCmd = value; }
        }
        private RelayCommand filterPNCmd;

        public RelayCommand FilterPNCmd
        {
            get
            {
                if (filterPNCmd == null)
                {
                    filterPNCmd = new RelayCommand(FilterPN);
                }
                return filterPNCmd;
            }
            set { filterPNCmd = value; }
        }
        private RelayCommand<string> comboPN_SelectionChangedCmd;

        public RelayCommand<string> ComboPN_SelectionChangedCmd
        {
            get
            {
                if (comboPN_SelectionChangedCmd == null)
                {
                    comboPN_SelectionChangedCmd = new RelayCommand<string>(ComboPN_SelectionChangedHandler);
                }
                return comboPN_SelectionChangedCmd;
            }
            set { comboPN_SelectionChangedCmd = value; }
        }
        private RelayCommand filterWOCmd;

        public RelayCommand FilterWOCmd
        {
            get
            {
                if (filterWOCmd == null)
                {
                    filterWOCmd = new RelayCommand(FilterWO);
                }
                return filterWOCmd;
            }
            set { filterWOCmd = value; }
        }
        private RelayCommand query;
        /// <summary>
        /// 查询工单命令
        /// </summary>
        public RelayCommand Query
        {
            get 
            {
                if (query==null)
                {
                    query = new RelayCommand(QueryWO);
                }
                return query; 
            }
            set { query = value; }
        }

        private RelayCommand export;
        /// <summary>
        /// 导出工单命令
        /// </summary>
        public RelayCommand Export
        {
            get 
            {
                if (export==null)
                {
                    export = new RelayCommand(ExportWO);
                }
                return export; 
            }
            set { export = value; }
        }
        private RelayCommand<SNEntity> copySnCmd;

        public RelayCommand<SNEntity> CopySnCmd
        {
            get 
            {
                if (copySnCmd==null)
                {
                    copySnCmd = new RelayCommand<SNEntity>(CopySnHandle);
                }
                return copySnCmd; 
            }
            set { copySnCmd = value; }
        }
        private RelayCommand<string> comboSnStatus_SelectionChangedCmd;
        /// <summary>
        /// 选择状态事件
        /// </summary>
        public RelayCommand<string> ComboSnStatus_SelectionChangedCmd
        {
            get 
            {
                if (comboSnStatus_SelectionChangedCmd==null)
                {
                    comboSnStatus_SelectionChangedCmd = new RelayCommand<string>(ComboSnStatusSelectionChangedHandle);
                }
                return comboSnStatus_SelectionChangedCmd; 
            }
            set { comboSnStatus_SelectionChangedCmd = value; }
        }
        private RelayCommand<string> comboWOState_SelectionChangedCmd;
        /// <summary>
        /// 选择的工单状态事件
        /// </summary>
        public RelayCommand<string> ComboWOState_SelectionChangedCmd
        {
            get {
                comboWOState_SelectionChangedCmd = comboWOState_SelectionChangedCmd ?? new RelayCommand<string>(ComboWOStateSelectionChangedHandler);
                return comboWOState_SelectionChangedCmd; }
            set { comboWOState_SelectionChangedCmd = value; }
        }

        #endregion

        #region 方法
        //页面加载
        private void LoadPage()
        {
            this.FillPNsToComboBox();
            SnStatus = new ObservableCollection<SnStatus>();
            SnStatus.Add(new SnStatus { Status = "全部" });
            SnStatus.Add(new SnStatus { Status = "入库" });
            SnStatus.Add(new SnStatus { Status = "未入库" });
            WOStates = new ObservableCollection<WOEntity> { 
            new WOEntity{CloseStatus="ALL",CloseStatusCn="全部"},
            new WOEntity{CloseStatus="Y",CloseStatusCn="关闭"},
            new WOEntity{CloseStatus="N",CloseStatusCn="未关闭"}
            };
        }
        /// <summary>
        /// 填充机种信息到下拉列表框中
        /// </summary>
        private void FillPNsToComboBox()
        {

            DataTable dtPNs = new DataTable();
            dtPNs = BusinessProcess.GetPNs(EnumPNType.All);
            PNs = new ObservableCollection<PartNumberEntity>();
            for (int i = 0; i < dtPNs.Rows.Count; i++)
            {
                PNs.Add(new PartNumberEntity
                {
                    PN = dtPNs.Rows[i]["PartNumber"].ToString()
                });
            }
        }

        /// <summary>
        /// 筛选机种下拉列表框中的数据
        /// </summary>
        private void FilterPN()
        {

            IsOpenComboPNDropDown = true;
            //当是第一次过滤的时候备份原始数据
            //这样是为了当不输入搜索条件时添加原始数据到列表中
            //当输入搜索条件时生成过滤集合绑定当下拉列表中
            if (isFirstFilterPN)
            {
                backupPNs = new ObservableCollection<PartNumberEntity>();
                backupPNs = PNs;
                isFirstFilterPN = false;
            }
            if (!string.IsNullOrEmpty(SearchPNText))
            {
                IEnumerable<PartNumberEntity> partNumberEntities = PNs.Where(s => s.PN.ToUpper().Contains(SearchPNText.ToUpper()));
                PNs = new ObservableCollection<PartNumberEntity>();
                foreach (var p in partNumberEntities)
                {
                    PNs.Add(p);
                }
            }
            else
            {
                PNs = backupPNs;
            }

        }
        /// <summary>
        /// 机种下拉框选项改变事件处理函数
        /// </summary>
        private void ComboPN_SelectionChangedHandler(string param)
        {
            if (param == null)
            {
                return;
            }
            DataTable dtWOs = new DataTable();
            DataTable dtPNInfo = new DataTable();
            dtWOs = BusinessProcess.GetWOsByPN(param);
            WOs = new ObservableCollection<WOEntity>();
            for (int i = 0; i < dtWOs.Rows.Count; i++)
            {
                WOs.Add(new WOEntity { WO = dtWOs.Rows[i]["WO"].ToString() });
            }
        }
        /// <summary>
        /// 序列号状态选择事件处理
        /// </summary>
        /// <param name="obj">状态</param>
        private void ComboSnStatusSelectionChangedHandle(string obj)
        {
           
            //判断传进来的参数是否为空
            if (obj!=null && obj!="")
            {
                //判断有没有完成查询
                if (IsCompletedQuery == true)
                {
                    ObservableCollection<SNEntity> tmpLastStatus = new ObservableCollection<SNEntity>(); //作为中间备份存储,加快处理速度.
                    LastStatus = new ObservableCollection<SNEntity>();
                    switch (obj)
                    {
                        case "全部":
                            //根据筛选条件将满足的数据添加到待导出报告数据集中
                            dtSnLastStatusReport = new DataTable();
                            dtSnLastStatusReport = dtSnLastStatus;
                            break;
                        case "入库":
                            var endRows = dtSnLastStatus.AsEnumerable().Where<DataRow>(x => x["IsEnd"].ToString() == "Y");
                            dtSnLastStatusReport = new DataTable();
                            dtSnLastStatusReport = endRows.Count() > 0 ? endRows.CopyToDataTable() : new DataTable();
                            break;
                        case "未入库":
                            var noEndRows = dtSnLastStatus.AsEnumerable().Where<DataRow>(x => x["IsEnd"].ToString() == "N");
                            dtSnLastStatusReport = new DataTable();
                            dtSnLastStatusReport = noEndRows.Count() > 0 ? noEndRows.CopyToDataTable() : new DataTable();
                            break;
                        default:
                            //忽略
                            break;
                    }
                    //根据筛选条件重新加载DataGrid
                    for (int i = 0; i < dtSnLastStatusReport.Rows.Count; i++)
                    {
                        tmpLastStatus.Add(new SNEntity
                        {
                            SN = dtSnLastStatusReport.Rows[i]["Sn"] == DBNull.Value ? "" : dtSnLastStatusReport.Rows[i]["Sn"].ToString(),
                            WO = dtSnLastStatusReport.Rows[i]["WO"] == DBNull.Value ? "" : dtSnLastStatusReport.Rows[i]["WO"].ToString(),
                            PN = dtSnLastStatusReport.Rows[i]["PN"] == DBNull.Value ? "" : dtSnLastStatusReport.Rows[i]["PN"].ToString(),
                            CompletedStation = dtSnLastStatusReport.Rows[i]["CompletedStation"] == DBNull.Value ? "" : dtSnLastStatusReport.Rows[i]["CompletedStation"].ToString(),
                            PretestStation = dtSnLastStatusReport.Rows[i]["PretestStation"] == DBNull.Value ? "" : dtSnLastStatusReport.Rows[i]["PretestStation"].ToString(),
                            IsEnd = dtSnLastStatusReport.Rows[i]["IsEnd"] == DBNull.Value ? "" : dtSnLastStatusReport.Rows[i]["IsEnd"].ToString(),
                            Actor = dtSnLastStatusReport.Rows[i]["Actor"] == DBNull.Value ? "" : dtSnLastStatusReport.Rows[i]["Actor"].ToString(),
                            CreateAt = dtSnLastStatusReport.Rows[i]["CreateAt"] == DBNull.Value ? "" : dtSnLastStatusReport.Rows[i]["CreateAt"].ToString()
                        });
                    }
                    LastStatus = tmpLastStatus;
                }
                else //查询过程中点击筛选按钮弹出的提示信息
                {
                    MessageBox.Show("正在查询数据,待查询完成后再筛选.", "软件温馨提示!", MessageBoxButton.OK, MessageBoxImage.Warning);
                }
            }
        }
        //工单状态筛选下拉列表框事件处理
        private void ComboWOStateSelectionChangedHandler(string obj)
        {

            //判断传进来的参数是否为空
            if (obj != null && obj != "")
            {
                //判断有没有完成查询
                if (IsCompletedQuery == true)
                {
                    ObservableCollection<WOEntity> tmpWOSource = new ObservableCollection<WOEntity>(); //作为中间备份存储,加快处理速度.
                    WOSource = new ObservableCollection<WOEntity>();
                    switch (obj)
                    {
                        //全部
                        case "ALL":
                            //根据筛选条件将满足的数据添加到待导出报告数据集中
                            dtWOReport = new DataTable();
                            dtWOReport = dtWO;
                            break;
                        //已经关闭的(CloseStatus=Y)
                        case "Y":
                            var closedRows = dtWO.AsEnumerable().Where<DataRow>(x => x["CloseStatus"].ToString() == "Y");
                            dtWOReport = new DataTable();
                            dtWOReport =closedRows.Count()>0? closedRows.CopyToDataTable():new DataTable();
                            break;
                        //未关闭的(CloseStatus=N)
                        case "N":
                            var noClosedRows = dtWO.AsEnumerable().Where<DataRow>(x => x["CloseStatus"].ToString() == "N");
                            dtWOReport = new DataTable();
                            dtWOReport =noClosedRows.Count()>0? noClosedRows.CopyToDataTable():new DataTable();
                            break;
                        default:
                            //忽略
                            break;
                    }
                    //根据筛选条件重新加载DataGrid
                    for (int i = 0; i < dtWOReport.Rows.Count; i++)
                    {
                        tmpWOSource.Add(new WOEntity
                        {
                            WO = dtWOReport.Rows[i]["WO"] == DBNull.Value ? "" : dtWOReport.Rows[i]["WO"].ToString(),
                            WODescription = dtWOReport.Rows[i]["WODescription"] == DBNull.Value ? "" : dtWOReport.Rows[i]["WODescription"].ToString(),
                            PN = dtWOReport.Rows[i]["PN"] == DBNull.Value ? "" : dtWOReport.Rows[i]["PN"].ToString(),
                            Flow = dtWOReport.Rows[i]["Flow"] == DBNull.Value ? "" : dtWOReport.Rows[i]["Flow"].ToString(),
                            StartSn = dtWOReport.Rows[i]["StartSn"] == DBNull.Value ? "" : dtWOReport.Rows[i]["StartSn"].ToString(),
                            EndSn = dtWOReport.Rows[i]["EndSn"] == DBNull.Value ? "" : dtWOReport.Rows[i]["EndSn"].ToString(),
                            Count = Convert.ToInt32(dtWOReport.Rows[i]["Count"] == DBNull.Value ? "0" : dtWOReport.Rows[i]["Count"].ToString() ?? "0"),
                            Completed = Convert.ToInt32(dtWOReport.Rows[i]["Completed"] == DBNull.Value ? "0" : dtWOReport.Rows[i]["Completed"].ToString() ?? "0"),
                            NoCompleted = Convert.ToInt32(dtWOReport.Rows[i]["NoCompleted"] == DBNull.Value ? "0" : dtWOReport.Rows[i]["NoCompleted"].ToString() ?? "0"),
                            CompletedPrint = Convert.ToInt32(dtWOReport.Rows[i]["CompletedPrint"] == DBNull.Value ? "0" : dtWOReport.Rows[i]["CompletedPrint"].ToString() ?? "0"),
                            CloseStatus = dtWOReport.Rows[i]["CloseStatus"] == DBNull.Value ? "" : dtWOReport.Rows[i]["CloseStatus"].ToString(),
                            OwnerManufacturer = dtWOReport.Rows[i]["OwnerManufacturer"] == DBNull.Value ? "" : dtWOReport.Rows[i]["OwnerManufacturer"].ToString(),
                            Actor = dtWOReport.Rows[i]["Actor"] == DBNull.Value ? "" : dtWOReport.Rows[i]["Actor"].ToString(),
                            CreateAt = dtWOReport.Rows[i]["CreateAt"] == DBNull.Value ? "" : dtWOReport.Rows[i]["CreateAt"].ToString()
                        });
                    }
                    WOSource = tmpWOSource;
                }
                else
                {
                    MessageBox.Show("正在查询数据,待查询完成后再筛选.", "软件温馨提示!", MessageBoxButton.OK, MessageBoxImage.Warning);
                }
            }
        }
        /// <summary>
        /// 筛选工单下拉列表框中的数据
        /// </summary>
        private void FilterWO()
        {

            IsOpenComboWODropDown = true;
            //当是第一次过滤的时候备份原始数据
            //这样是为了当不输入搜索条件时添加原始数据到列表中
            //当输入搜索条件时生成过滤集合绑定当下拉列表中
            if (isFirstFilterWO)
            {
                backupWOs = new ObservableCollection<WOEntity>();
                backupWOs = WOs;
                isFirstFilterWO = false;
            }
            if (!string.IsNullOrEmpty(SearchWOText) && WOs!=null)
            {
                IEnumerable<WOEntity> WOEntities = WOs.Where(s => s.WO.ToUpper().Contains(SearchWOText.ToUpper()));
                WOs = new ObservableCollection<WOEntity>();
                foreach (var w in WOEntities)
                {
                    WOs.Add(w);
                }
            }
            else
            {
                WOs = backupWOs;
            }

        }
        /// <summary>
        /// 查询工单信息
        /// </summary>
        private async void QueryWO()
        {
            string retMsg = string.Empty;
            string[] arrayMsg = new string[] { };
            List<DataTable> lstDt = new List<DataTable>();
            try
            {
                if (!IsCompletedExport)
                {
                    MessageBox.Show("正在导报告,待导出完成后再点击查询按钮.", "软件温馨提示!", MessageBoxButton.OK, MessageBoxImage.Warning);
                    return;
                }
                if (!IsCheckedAll)
                {
                    if (string.IsNullOrEmpty(this.SN)&& string.IsNullOrEmpty(this.SearchPNText)&&string.IsNullOrEmpty(this.SearchWOText))
                    {
                        MessageBox.Show("请输入查询参数或者点击查询一年数据复选框.", "软件温馨提示!", MessageBoxButton.OK, MessageBoxImage.Warning);
                        return;
                    }
                }
                dtWO = new DataTable();
                dtSnLastStatus = new DataTable();
                dtWOReport = new DataTable();
                dtSnLastStatusReport = new DataTable();
                dtTestLogs = new DataTable();
                //开启多线程防止页面假死
                await Task.Run(() =>
                {
                    IsCompletedQuery = false;//将完成查询的标记改为false这样防止用户再没有完成查询之前点击导出功能
                    //禁用查询按钮防止二次点击
                    this.IsEnabledQueryButton = false;
                    //打开动画
                    this.IsVisibleLoading = Visibility.Visible;
                    //关闭TestLog面板
                    this.TestLogPanelVisibile = Visibility.Collapsed;
                    WOSource = new ObservableCollection<WOEntity>();
                    LastStatus = new ObservableCollection<SNEntity>();
                    TestLogs = new ObservableCollection<TrackingEntity>();
                    SNEntity snEntity = new SNEntity()
                    {
                        SN = this.SN ?? "",
                        PN = this.SearchPNText ?? "",
                        WO = this.SearchWOText ?? ""
                    };
                    //当选择查询所有信息时清空所有输入的信息
                    if (IsCheckedAll)
                    {
                        snEntity = new SNEntity() { SN = "", PN = "", WO = "" };
                    }
                    retMsg = BusinessProcess.QueryWODetails(snEntity, lstDt);
                    arrayMsg = retMsg.Split('|');
                    if (arrayMsg[0] == "OK")
                    {
                        if (lstDt.Count > 0)
                        {
                            if (lstDt.Count == 1)
                            {
                                dtWO = lstDt[0];
                                dtWOReport = lstDt[0];
                            }
                            else if (lstDt.Count == 2)
                            {
                                dtWO = lstDt[0];
                                dtWOReport = lstDt[0];
                                dtSnLastStatus = lstDt[1];
                                dtSnLastStatusReport = lstDt[1];
                            }
                            else if (lstDt.Count == 3)
                            {
                                dtWO = lstDt[0];
                                dtWOReport = lstDt[0];
                                dtSnLastStatus = lstDt[1];
                                dtSnLastStatusReport = lstDt[1];
                                dtTestLogs = lstDt[2];
                                this.TestLogPanelVisibile = Visibility.Visible;
                            }
                            for (int i = 0; i < dtWO.Rows.Count; i++)
                            {
                                Application.Current.Dispatcher.BeginInvoke((System.Action)(() =>
                                {
                                    WOSource.Add(new WOEntity
                                    {
                                        WO = dtWO.Rows[i]["WO"] == DBNull.Value ? "" : dtWO.Rows[i]["WO"].ToString(),
                                        WODescription = dtWO.Rows[i]["WODescription"] == DBNull.Value ? "" : dtWO.Rows[i]["WODescription"].ToString(),
                                        PN = dtWO.Rows[i]["PN"] == DBNull.Value ? "" : dtWO.Rows[i]["PN"].ToString(),
                                        Flow = dtWO.Rows[i]["Flow"] == DBNull.Value ? "" : dtWO.Rows[i]["Flow"].ToString(),
                                        StartSn = dtWO.Rows[i]["StartSn"] == DBNull.Value ? "" : dtWO.Rows[i]["StartSn"].ToString(),
                                        EndSn = dtWO.Rows[i]["EndSn"] == DBNull.Value ? "" : dtWO.Rows[i]["EndSn"].ToString(),
                                        Count = Convert.ToInt32(dtWO.Rows[i]["Count"]==DBNull.Value?"0":dtWO.Rows[i]["Count"].ToString() ?? "0"),
                                        Completed = Convert.ToInt32(dtWO.Rows[i]["Completed"]==DBNull.Value?"0":dtWO.Rows[i]["Completed"].ToString() ?? "0"),
                                        NoCompleted = Convert.ToInt32(dtWO.Rows[i]["NoCompleted"]==DBNull.Value?"0":dtWO.Rows[i]["NoCompleted"].ToString() ?? "0"),
                                        CompletedPrint =Convert.ToInt32(dtWO.Rows[i]["CompletedPrint"]==DBNull.Value?"0": dtWO.Rows[i]["CompletedPrint"].ToString()?? "0"),
                                        CloseStatus = dtWO.Rows[i]["CloseStatus"]==DBNull.Value?"": dtWO.Rows[i]["CloseStatus"].ToString(),
                                        OwnerManufacturer = dtWO.Rows[i]["OwnerManufacturer"] == DBNull.Value ? "" : dtWO.Rows[i]["OwnerManufacturer"].ToString(),
                                        Actor = dtWO.Rows[i]["Actor"] == DBNull.Value ? "" : dtWO.Rows[i]["Actor"].ToString(),
                                        CreateAt = dtWO.Rows[i]["CreateAt"] == DBNull.Value ? "" : dtWO.Rows[i]["CreateAt"].ToString()
                                    });
                                }));
                                Thread.Sleep(TimeSpan.FromMilliseconds(150));
                            }
                            ObservableCollection<SNEntity> tmpLastStatus = new ObservableCollection<SNEntity>();
                            for (int i = 0; i < dtSnLastStatus.Rows.Count; i++)
                            {
                                tmpLastStatus.Add(new SNEntity
                                {
                                    SN = dtSnLastStatus.Rows[i]["Sn"].ToString(),
                                    WO = dtSnLastStatus.Rows[i]["WO"].ToString(),
                                    PN = dtSnLastStatus.Rows[i]["PN"].ToString(),
                                    CompletedStation = dtSnLastStatus.Rows[i]["CompletedStation"].ToString(),
                                    PretestStation = dtSnLastStatus.Rows[i]["PretestStation"].ToString(),
                                    IsEnd = dtSnLastStatus.Rows[i]["IsEnd"].ToString(),
                                    Actor = dtSnLastStatus.Rows[i]["Actor"].ToString(),
                                    CreateAt = dtSnLastStatus.Rows[i]["CreateAt"].ToString()

                                    //SN = dtSnLastStatus.Rows[i]["Sn"] == DBNull.Value ? "" : dtSnLastStatus.Rows[i]["Sn"].ToString(),
                                    //WO = dtSnLastStatus.Rows[i]["WO"] == DBNull.Value ? "" : dtSnLastStatus.Rows[i]["WO"].ToString(),
                                    //PN = dtSnLastStatus.Rows[i]["PN"] == DBNull.Value ? "" : dtSnLastStatus.Rows[i]["PN"].ToString(),
                                    //CompletedStation = dtSnLastStatus.Rows[i]["CompletedStation"] == DBNull.Value ? "" : dtSnLastStatus.Rows[i]["CompletedStation"].ToString(),
                                    //PretestStation = dtSnLastStatus.Rows[i]["PretestStation"] == DBNull.Value ? "" : dtSnLastStatus.Rows[i]["PretestStation"].ToString(),
                                    //IsEnd = dtSnLastStatus.Rows[i]["IsEnd"] == DBNull.Value ? "" : dtSnLastStatus.Rows[i]["IsEnd"].ToString(),
                                    //Actor = dtSnLastStatus.Rows[i]["Actor"] == DBNull.Value ? "" : dtSnLastStatus.Rows[i]["Actor"].ToString(),
                                    //CreateAt = dtSnLastStatus.Rows[i]["CreateAt"] == DBNull.Value ? "" : dtSnLastStatus.Rows[i]["CreateAt"].ToString()
                                });
                             
                               // Thread.Sleep(TimeSpan.FromMilliseconds(5));
                            }
                            Application.Current.Dispatcher.BeginInvoke((System.Action)(() =>
                            {
                                LastStatus = tmpLastStatus;
                            }));
                            for (int i = 0; i < dtTestLogs.Rows.Count; i++)
                            {
                                Application.Current.Dispatcher.BeginInvoke((System.Action)(() =>
                                {
                                    TestLogs.Add(new TrackingEntity
                                    {
                                        Sn = dtTestLogs.Rows[i]["Sn"].ToString() ?? "",
                                        WO = dtTestLogs.Rows[i]["WO"].ToString() ?? "",
                                        Station = dtTestLogs.Rows[i]["Station"].ToString() ?? "",
                                        Result = dtTestLogs.Rows[i]["Result"].ToString() ?? "",
                                        FailDescription = dtTestLogs.Rows[i]["FailDescription"].ToString() ?? "",
                                        FailValue = dtTestLogs.Rows[i]["FailValue"].ToString() ?? "",
                                        EquipmentName = dtTestLogs.Rows[i]["EquipmentName"].ToString() ?? "",
                                        TestSequence = dtTestLogs.Rows[i]["TestSequence"].ToString() ?? "",
                                        StartTime = dtTestLogs.Rows[i]["StartTime"].ToString() ?? "",
                                        StopTime = dtTestLogs.Rows[i]["StopTime"].ToString() ?? "",
                                        Duration = dtTestLogs.Rows[i]["Duration"].ToString() ?? "",
                                        Shift = dtTestLogs.Rows[i]["Shift"].ToString() ?? "",
                                        Actor = dtTestLogs.Rows[i]["Actor"].ToString() ?? "",
                                        Year = dtTestLogs.Rows[i]["Year"].ToString() ?? "",
                                        Month = dtTestLogs.Rows[i]["Month"].ToString() ?? "",
                                        Week = dtTestLogs.Rows[i]["Week"].ToString() ?? "",
                                        CreateAt = dtTestLogs.Rows[i]["CreateAt"].ToString() ?? ""
                                    });
                                }));
                                Thread.Sleep(TimeSpan.FromMilliseconds(100));
                            }
                            //隐藏动画
                            this.IsVisibleLoading = Visibility.Collapsed;

                        }
                        //清空页面数据
                        this.PN = "";
                        this.WO = "";
                        this.SN = "";
                    }
                    else
                    {
                        MessageBox.Show(arrayMsg[1], "软件温馨提示!", MessageBoxButton.OK, MessageBoxImage.Warning);
                    }
                    this.IsEnabledQueryButton = true;
                    this.IsCompletedQuery = true;//将完成查询的状态改为true表示查询成功可以导出数据
                });
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(ex.Message, ex);
                throw new Exception(ex.Message);
            }
        }
        /// <summary>
        /// 导出工单信息
        /// </summary>
        private async void ExportWO()
        {
            if (dtWOReport.Rows.Count==0 && dtSnLastStatusReport.Rows.Count==0)
            {
                MessageBox.Show("没有需要导出的数据","软件温馨提示!",MessageBoxButton.OK,MessageBoxImage.Information);
                return;
            }
            if (!IsCompletedQuery)
            {
                MessageBox.Show("正在查询数据,待查询完成后再点击导出按钮.", "软件温馨提示!", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }
            IsCompletedExport = false;//将完成导出状态改成false防止用户再导报告时点击查询数据
            //保存数据之前先关闭Excel
            BusinessProcess.KillProcess("EXCEL");
            this.IsEnabledExportButton = false;
            //创建Excel  
            Microsoft.Office.Interop.Excel.Application excelApp = new Microsoft.Office.Interop.Excel.Application();
            Workbook excelWB = excelApp.Workbooks.Add(System.Type.Missing);    //创建工作簿（WorkBook：即Excel文件主体本身）  
            Worksheet excelWS = (Worksheet)excelWB.Worksheets[1];   //创建工作表（即Excel里的子表sheet） 1表示在子表sheet1里进行数据导出  
            //excelWS.Cells.NumberFormat = "@";     //  如果数据中存在数字类型 可以让它变文本格式显示  
            //将数据导入到工作表的单元格
            await Task.Run(() => {
                //显示加载动画
                this.IsVisibleLoading = Visibility.Visible;
                for (int i = 0; i < dtWOReport.Columns.Count; i++)
                {
                    excelWS.Cells[1, i + 1] = dtWOReport.Columns[i].ColumnName;
                }

                for (int i = 0; i < dtWOReport.Rows.Count; i++)
                {
                    for (int j = 0; j < dtWOReport.Columns.Count; j++)
                    {
                        excelWS.Cells[i + 2, j + 1] = dtWOReport.Rows[i][j].ToString();   //Excel单元格第一个从索引1开始 
                    }
                }
                //创建工作表（Worksheet：工作表，即Excel里的子表sheet）
                excelWS = (Microsoft.Office.Interop.Excel.Worksheet)excelWB.Worksheets.Add(System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value);  
                //设置表名
                excelWS.Name = "SnLastStatus"; 
                //将数据导入到工作表的单元格
                for (int i = 0; i < dtSnLastStatusReport.Columns.Count; i++)
                {
                    excelWS.Cells[1, i + 1] = dtSnLastStatusReport.Columns[i].ColumnName;
                }

                for (int i = 0; i < dtSnLastStatusReport.Rows.Count; i++)
                {
                    for (int j = 0; j < dtSnLastStatusReport.Columns.Count; j++)
                    {
                        excelWS.Cells[i + 2, j + 1] = dtSnLastStatusReport.Rows[i][j].ToString();   //Excel单元格第一个从索引1开始 
                    }
                }
                //关闭加载动画
                this.IsVisibleLoading = Visibility.Collapsed;
            });
          
            //使用对话框让用户选择保存位置和填写保存的文件名
            Microsoft.Win32.SaveFileDialog sfd = new Microsoft.Win32.SaveFileDialog();

            sfd.Filter = "Excel工作簿(*.xlsx)|*.xlsx";

            sfd.FilterIndex = 1;

            sfd.RestoreDirectory = true;

            if (sfd.ShowDialog() == true)
            {
                string localFilePath = sfd.FileName.ToString(); //获得文件路径
                string fileNameExt = localFilePath.Substring(localFilePath.LastIndexOf("\\") + 1); //获取文件名，不带路径

                //获取文件路径，不带文件名
                //FilePath = localFilePath.Substring(0, localFilePath.LastIndexOf("\\"));
                //给文件名前加上时间
                //newFileName = DateTime.Now.ToString("yyyyMMdd") + fileNameExt;
                //在文件名里加字符
                //saveFileDialog1.FileName.Insert(1,"dameng");
                //System.IO.FileStream fs = (System.IO.FileStream)sfd.OpenFile();//输出文件fs输出带文字或图片的文件，就看需求了
                excelWB.SaveAs(localFilePath);  //将其进行保存到指定的路径  
                excelWB.Close();
                excelApp.Quit();  //KillAllExcel(excelApp); 释放可能还没释放的进程
                MessageBox.Show("导出表格成功!");
                System.Diagnostics.Process.Start(localFilePath);//保存完成后  打开文件
            }
            this.IsCompletedExport = true;
            this.IsEnabledExportButton = true;
        }
        /// <summary>
        /// 拷贝序列号信息到剪贴板
        /// </summary>
        /// <param name="obj">选中的序列号实体类</param>
        private void CopySnHandle(SNEntity obj)
        {
            Clipboard.SetText(obj.SN);
        }
        #endregion
    }
}
